<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            信号监控
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
      <div id="shinebody" style='width: 100%;height: 10rem;background-color: #bdbdbd;float: left;margin-right: 1%'>
        <!-- #12599a -->
        <img id="equipPic" style='width: 98%;height: 96%;margin-left: 1%;margin-top: 1%;' />
      </div>
        <ul class="aui-list aui-form-list" id="attrListHtml">
<li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>停止信号</div><input type='text' class='aui-input' id='OPC_P1_Stop' disabled='true' value='true'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>启动信号</div><input type='text' class='aui-input' id='OPC_P1_Start' disabled='true' value='true'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>故障信号</div><input type='text' class='aui-input' id='OPC_P1_Fault' disabled='true' value='false'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>急停信号</div><input type='text' class='aui-input' id='OPC_P1_EStop' disabled='true' value='true'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>有功功率</div><input type='text' class='aui-input' id='OPC_CPNY_YGGL' disabled='true' value='1234567.0'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>电流1</div><input type='text' class='aui-input' id='OPC_CPNY_DL1' disabled='true' value='123.0'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>电压1</div><input type='text' class='aui-input' id='OPC_CPNY_DY1' disabled='true' value='0.0'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>条码1</div><input type='text' class='aui-input' id='OPC_P1_JG_TM1' disabled='true' value='456'></div></li><li class='aui-list-item'><div class='aui-list-item-inner'><div class='aui-list-item-label' style='width:60%;'>检测系统1完成信号</div><input type='text' class='aui-input' id='OPC_TestSys1_Complete' disabled='true' value='true'></div></li>
        </ul>
        <div style="width:100%;margin-top:2%;"></div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/mqttws31.js"></script>
<script type="text/javascript">

    var code; //菜单路由参数 信号点编码

    var port = 61623;
    var username = "";
    var password = "";
    var host = "";

    var topic="";
    var equipCode="";

    var client;

    var colorArr=['red','yellow','green'];
    var indexColor=0;


    apiready = function() {
      var query = api.pageParam.query;
      code = query.code;
      //code应为信号点模板编码+/+设备编码
      if(code==undefined||code==null||code==''){
        api.toast({
            msg: '当前菜单未维护信号点编码，为无效菜单！',
            duration: 3000
        });
        return;
      }

      var arr = code.split("/");
      if(arr.length<2){
        api.toast({
            msg: '当前菜单未维护设备编码，为无效菜单！',
            duration: 3000
        });
        return;
      }
      topic = arr[0];
      equipCode = arr[1];
      getEquipPic();//获取设备图片
      //获取当前信号所监控的参数
      getPointAttr();


    }



    function getEquipPic(){
      var serverUrl = localStorage.getItem('serverUrl');
      var un = localStorage.getItem("un");
      var url = serverUrl + "/app/getEquipPic";
      var data = {
          values: {
              un: un,
              appVersion: api.appVersion,
              equipCode:equipCode
          }
      };
      api.ajax({
          url: url,
          method: 'post',
          dataType: 'json',
          timeout: 30,
          returnAll: false,
          data: data
      }, function(ret, err) {
          if (ret) {
              var data = JSON.stringify(ret);
              var myobj = eval("(" + data + ")");
              if (myobj.code == '0') {

                console.log("8888:"+JSON.stringify(myobj.addr));
                document.getElementById("equipPic").setAttribute("src",myobj.addr);

              }else if(myobj.code=='1'){
                api.toast({
                      msg: myobj.message,
                      duration: 3000
                  });
              }
               else {
                  api.toast({
                      msg: myobj.message,
                      duration: 3000
                  });
              }
          }
      });
    }

    function getPointAttr(){
      console.log("8888888");
      var serverUrl = localStorage.getItem('serverUrl');
      var un = localStorage.getItem("un");
      var url = serverUrl + "/app/getPointAttr";
      var data = {
          values: {
              un: un,
              appVersion: api.appVersion,
              pointCode:equipCode
          }
      };
      api.ajax({
          url: url,
          method: 'post',
          dataType: 'json',
          timeout: 30,
          returnAll: false,
          data: data
      }, function(ret, err) {
          if (ret) {
              var data = JSON.stringify(ret);
              var myobj = eval("(" + data + ")");
              if (myobj.code == '0') {
                var list = myobj.list;
                var html = "";
                console.log(JSON.stringify(list));
                for (var i = 0; i < list.length; i++) {
                    html += "<li class='aui-list-item'>";
                    html += "<div class='aui-list-item-inner'>";
                    html += "<div class='aui-list-item-label' style='width:60%;'>" + list[i].annotation + "</div>";
                    html += "<input type='text'  class='aui-input' id='" + list[i].tagname + "' disabled='true' value='"+list[i].tagvalue+"'>";
                    html += "</div>";
                    html += "</li>";

                }
                console.log(JSON.stringify(html));
                $api.html($api.byId("attrListHtml"), html);
                //查询,mqtt服务器ip端口
                getCombox();
              }else if(myobj.code == '1'){
                api.toast({
                      msg: myobj.message,
                      duration: 3000
                  });
              }
               else {
                  api.toast({
                      msg: myobj.message,
                      duration: 3000
                  });
              }
          }
      });

    }

    //查询服务器ip
    function getCombox() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUdiList";
        var data = {
            values: {
                code: "MQTT",
                appVersion: api.appVersion,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function(ret, err) {
          console.log("getCombox:"+JSON.stringify(ret));
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == "0") {
                    var mqttList = eval(myobj.list);

                    for (var i = 0; i < mqttList.length; i++) {
                        if (mqttList[i].value == 'host') {
                            host = mqttList[i].label;
                        } else if (mqttList[i].value == 'port') {
                            port = parseInt(mqttList[i].label);
                        } else if (mqttList[i].value == 'username') {
                            username = mqttList[i].label;
                        } else if (mqttList[i].value == 'password') {
                            password = mqttList[i].label;
                        }
                    }
                    console.log("mqttMsg");
                    //订阅mqtt
                    mqttMsg();

                    //失败
                } else if (myobj.code == "1") {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                api.toast({
                    msg: JSON.stringify(err),
                    duration: 3000
                });
            }
        });
    }

    //连接MQTT
    function mqttMsg() {
      console.log("mqttMsg111");
        client = new Paho.MQTT.Client(host, port, '/mqtt', 'webSocket' + getUuid());
        console.log("mqttMsg222");
        client.onConnectionLost = onConnectionLost;
        client.onMessageArrived = onMessageArrived;
        client.connect({
            userName: username,
            password: password,
            onSuccess: onConnect
        });
    }

    //连接成功后事件
    function onConnect() {
      console.log("onConnect");
        client.subscribe(code, {
            qos: 2
        });
    }

    //断开连接
    function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
            console.log("断开连接:" + responseObject.errorMessage);
        } else {
            console.log("断开连接:" + responseObject.errorCode);
        }
    }

    //订阅后回调函数
    function onMessageArrived(message) {
      console.log("onMessageArrived:"+JSON.stringify(message));
        var topic = message.destinationName;
        var decodedString = byteToString(message.payloadBytes);
        var map = eval("(" + decodedString + ")");
        console.log("topic:"+topic);
console.log("onMessageArrived22:"+JSON.stringify(map));
        //处理数据
        dealData(topic, map)
    }

    function dealData(topic, map) {
        // var arr = topic.split("/");
        // topic = arr[arr.length - 1];
        for (var key in map) {
                $("#" + key).val(map[key]);
                console.log("background-color:"+$("input").css("background-color"));
                var colorNow=$("#" + key).css("background-color");
                if(colorNow!='rgb(236, 197, 18)'){
                  $("#" + key).css("background-color","rgb(236, 197, 18)");
                }else if(colorNow!='rgb(99, 230, 186)'){
                  $("#" + key).css("background-color","rgb(99, 230, 186)");
                }
        }

    }

    function byteToString(buffer) {
        let encodedString = String.fromCodePoint.apply(
            null,
            new Uint8Array(buffer)
        )
        let decodedString = decodeURIComponent(escape(encodedString)) //没有这一步中文会乱码
        return decodedString
    }

    //生成32位随机数
    function getUuid() {
        var str = 'abcdefghijklmnopqrstuvwxyz0123456789';
        var result = '';
        for (var i = 0; i < 32; i++) {
            result += str[parseInt(Math.random() * str.length)];
        }
        return result;
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>
